﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using xVal.ServerSide;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Northwinddemo.BusinessLayer
{
    internal static class DataAnnotationsValidationRunner
    {

        public static List<ErrorInfo> GetErrors(object instance)
        {
            TypeDescriptor.AddProvider(new AssociatedMetadataTypeTypeDescriptionProvider(instance.GetType()), instance);
            return (from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>()
                    from attribute in prop.Attributes.OfType<ValidationAttribute>()
                    where !attribute.IsValid(prop.GetValue(instance))
                    select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty), instance)).ToList();
        }
    }
}
